package edu.stu.mall.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import edu.stu.mall.databinding.ItemRecommendedProductBinding
import edu.stu.mall.repository.data.RecommendedProductDataItem
import edu.stu.mall.service.loadImage

class RecommendedProductAdapter :
    RecyclerView.Adapter<RecommendedProductAdapter.RecommendedProductViewHolder>() {

    private var dataList: List<RecommendedProductDataItem> = mutableListOf()

    // 1.定义一个接口用于处理了点击事件
    interface RecommendItemClickListener {
        fun onItemClick(item: RecommendedProductDataItem)
    }

    // 2.定义一个变量用于存储点击事件的监听器
    private var itemClickListener: RecommendItemClickListener? = null

    // 3.注册点击事件监听方法
    fun setItemClickListener(listener: RecommendItemClickListener?) {
        this.itemClickListener = listener
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(list: List<RecommendedProductDataItem>?) {
        if (!list.isNullOrEmpty()) {
            dataList = list
            notifyDataSetChanged()
        }
    }


    class RecommendedProductViewHolder(binding: ItemRecommendedProductBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var itemBinding: ItemRecommendedProductBinding

        init {
            itemBinding = binding
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ) = RecommendedProductViewHolder(
        ItemRecommendedProductBinding.inflate(
            LayoutInflater.from(parent.context),
            parent, false
        )
    )

    override fun getItemCount(): Int = dataList.size

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecommendedProductViewHolder, position: Int) {

        val data = dataList[position]

        holder.itemBinding.apply {
            item = data
            loadImage(data.pic, ivPic)
            tvPrice.text = "￥：${
                if (data.price!! % 1 == 0.0) {
                    data.price.toInt()
                } else {
                    data.price.toString()
                }
            }"
            tvPrice.setTextColor(Color.RED)
            // 4.调用监听器的onItemClick方法
            root.setOnClickListener {
                itemClickListener?.onItemClick(data)
            }
        }
    }
}